/*
 *
 *  *  Copyright (c), utrix (idea110@163.com).
 *  *  <p>
 *  *  Licensed under the GNU Lesser General Public License 3.0 (the "License");
 *  *  you may not use this file except in compliance with the License.
 *  *  You may obtain a copy of the License at
 *  *  <p>
 *  * https://www.gnu.org/licenses/lgpl.html
 *  *  <p>
 *  * Unless required by applicable law or agreed to in writing, software
 *  * distributed under the License is distributed on an "AS IS" BASIS,
 *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  * See the License for the specific language governing permissions and
 *  * limitations under the License.
 *
 */

package priv.utrix.micro.config;

import com.google.common.base.Preconditions;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import priv.utrix.micro.constant.AuthConstants;
import priv.utrix.micro.dto.SecurityUserDto;
import priv.utrix.micro.dto.SysUserDTO;
import priv.utrix.micro.dubbo.SysUserDubbo;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * 用户详情信息配置类
 *
 * @author utrix
 * @since 2020/9/28 16:34
 */
@Configuration
public class UserDetailsServiceConfig implements UserDetailsService {

    /**
     * 缺省为 failover 重试
     * 失败自动切换，当出现失败，重试其它服务器
     */
    @DubboReference
    SysUserDubbo userDubbo;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserDTO userDTO = userDubbo.getByUsername(username);
        Preconditions.checkNotNull(userDTO);

        String password = userDTO.getPassword();
        Preconditions.checkNotNull(password, "The password stored in the database is empty and the system is abnormal");

        // 拼接角色前缀
        List<GrantedAuthority> authorityList = Optional.ofNullable(userDTO.getRoleIds()).map(roles -> {
            Arrays.parallelSetAll(roles, value -> AuthConstants.AUTHORITY_PREFIX + value);
            return roles;
        }).map(AuthorityUtils::createAuthorityList).orElseGet(Collections::emptyList);

        return new SecurityUserDto(username, AuthConstants.BCRYPT + password, authorityList, userDTO.getId(), userDTO.getAuthorityCodeList());
    }
}
